<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/27 0027
 * Time: 上午 10:34
 */
namespace app\api\controller;

use app\admin\model\Advertise;
use app\api\service\Adpay;
use app\api\service\AdWxNotify;
use app\common\Helper;
use app\common\model\Advertiselocal;
use app\common\model\Advertiselocalconnect;
use app\common\model\Advertisestoreconnect;
use app\common\model\Advertiseticketconnect;
use app\common\validate\CreateAdvertise;
use think\Db;
use think\Exception;
use think\Request;

class Ad extends Base{

    /**
     * 获取广告位信息
     * @return \think\response\Json
     */
    public function getAdvertiseLocalInfo(){
        $Advertiselocal = Advertiselocal::where('status',1)->select();
        if($Advertiselocal){

            $nowtime = date('Y-m-d H:i:s',time());
            $nowtimem = date('Y-m-d H:i:s',strtotime('+1 day'));
            foreach ($Advertiselocal as &$v){
                $Advertiselocalconnect = Advertiselocalconnect::where('advertiseLocalId',$v['id'])->select();
                if($Advertiselocalconnect){
                    $endtime = [];
                    foreach ($Advertiselocalconnect as $value){
                        $Advertise = Advertise::where('id',$value['advertiseId'])->where('payStatus',1)->find();
                        if($Advertise){
                            array_push($endtime,$Advertise['endTime']);
                        }else{
                            array_push($endtime,$nowtimem);
                        }
                        $maxendtime = max($endtime);
                        $v['launchTime'] = $maxendtime;
                    }
                }else{
                    $v['launchTime'] = $nowtimem;
                }
            }
            foreach ($Advertiselocal as &$v){
                if($v['launchTime'] < $nowtime){
                    $v['launchTime'] = $nowtimem;
                }
            }
            return show(config('status.SUCCESS_STATUS'),'ok',$Advertiselocal);
        }else{
            return show(2,'平台暂无广告位',NULL);
        }
    }


    /**
     * 广告订单创建
     * @param Request $request
     * @return \think\response\Json
     */
    public function createAdvertise(Request $request){
        (new CreateAdvertise())->goCheck();
        $param = $request->param();
        $id =  $this->createAdorder($param);
        return show(config('status.SUCCESS_STATUS'),'ok',$id);
    }

    private function createAdorder($param){
        $advertise = $param['advertise'];
        Db::startTrans();
        try{
            $AdvertiseModel = new Advertise();
            $id = Helper::getUUID();
            $AdvertiseModel->id = $id;
            $AdvertiseModel->advertiseTitle = $advertise['advertiseTitle'];
            $AdvertiseModel->advertiseCost = $advertise['advertiseCost'];
            $AdvertiseModel->advertiseImgUrl = $advertise['advertiseImgUrl'];
            $AdvertiseModel->advertiseUrlStatus = $advertise['advertiseUrlStatus'];
            $AdvertiseModel->circleTime = $advertise['circleTime'];
            $adTime = $this->getsdTime($advertise['circleTime'],$param['advertiseLocalId']);
            $AdvertiseModel->startTime = $adTime['startTime'];
            $AdvertiseModel->endTime = $adTime['endTime'];
            $AdvertiseModel->save();
            $Advertiselocalconnect = new Advertiselocalconnect();
            $Advertiselocalconnect->advertiseLocalId = $param['advertiseLocalId'];
            $Advertiselocalconnect->advertiseId = $id;
            $Advertiselocalconnect->save();
            $Advertisestoreconnect = new Advertisestoreconnect();
            $Advertisestoreconnect->storeId = $param['storeId'];
            $Advertisestoreconnect->advertiseId = $id;
            $Advertisestoreconnect->save();
            if($advertise['advertiseUrlStatus'] ==1){
                $Advertiseticketconnect = new Advertiseticketconnect();
                $Advertiseticketconnect->ticketId = $advertise['advertiseUrl'];
                $Advertiseticketconnect->advertiseId = $id;
                $Advertiseticketconnect->save();
            }
            Db::commit();
            return $id;
        }catch (Exception $ex){
            Db::rollback();

        }

    }

    /**
     * 广告订单支付入口
     * @param Request $request
     * @return \think\response\Json
     */
    public function adPayment(Request $request){
        $param = $request->param();
        if(empty($param['advertiseId'])){
            return show(config('status.ERROR_STATUS'),'缺少订单广告id','缺少订单广告id');
        }
        $adpay = new Adpay($param);
        return $adpay->pay();
    }

    //广告支付回调函数
    public function receiveNotify(){
        $notify = new AdWxNotify();
        $notify->Handle();
    }

    //获取广告列表
    public function getAdvertiseList(Request $request){
        $param = $request->param();
        if(empty($param['storeId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $res = Db::table('advertisestoreconnect')->alias('a')->join('advertise b','a.advertiseId=b.id')->where('a.storeId',$param['storeId'])->where('b.payStatus',1)->order('b.createTime DESC')->select();
        if($res){
            return show(config('status.SUCCESS_STATUS'),'ok',$res);
        }else{
            return show(2,'暂无广告',NULL);
        }

    }

    /**
     * 获取该广告位可投放排期
     * @param $circleTime 投放天数
     * @param $advertiseLocalId  广告位ID
     * @return array|\think\response\Json
     */
    private function getsdTime($circleTime,$advertiseLocalId){
        $Advertiselocal = Advertiselocal::where(['id'=>$advertiseLocalId,'status'=>1])->find();
        if($Advertiselocal){
            $nowtime = date('Y-m-d',time());
            $nowtimem = date('Y-m-d',strtotime('+1 day'));
            $stime = (int)$circleTime*24*3600;
            $Advertiselocalconnect = Advertiselocalconnect::where('advertiseLocalId',$advertiseLocalId)->select();
            $data = [];
            if($Advertiselocalconnect){
                $endtime = [];
                foreach ($Advertiselocalconnect as &$v){
                    $Advertise = Advertise::where('id',$v['advertiseId'])->where('payStatus',1)->find();
                    if($Advertise){
                        array_push($endtime,$Advertise['endTime']);
                    }else{
                        array_push($endtime,$nowtimem);
                    }
                    $maxendtime = max($endtime);
                    $data['startTime'] = $maxendtime;
                }
            }else{
                $data['startTime'] = $nowtimem;
            }
            if($data['startTime'] < $nowtime){
                $data['startTime'] = $nowtimem;
            }
            $endTime = strtotime($data['startTime']) + $stime;
            $data['endTime'] = date('Y-m-d',$endTime);
            return $data;
        }else{
            return show(config('status.ERROR_STATUS'),'该广告位已经被删除','该广告位已经被删除');
        }
    }
}